package com.ruoyi.protocol.controller;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.protocol.controller.interf.IProtocolWrapper;
import com.ruoyi.protocol.domin.ProtocolDTO;
import com.ruoyi.protocol.frame.EProtocol;
import com.zxq.factory.utils.CrcUtils;
import com.zxq.memory.ByteCombination;
import lombok.extern.slf4j.Slf4j;
import org.apache.xmlbeans.impl.util.HexBin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController("protocol")
@Slf4j
public class ProtocolController implements IProtocolWrapper {



    /**
     * 打包协议
     * @param protocolDTO 协议数据
     * @return
     */
    @Override
    public ProtocolDTO wrapperProtocol(@RequestBody ProtocolDTO protocolDTO) {
       log.info("protocol:" + JSON.toJSONString(protocolDTO));

       ProtocolDTO rst = new ProtocolDTO();
       Integer protocol =  protocolDTO.getProtocolId();
       rst.setProtocolId(protocol);
       EProtocol eProtocol =  EProtocol.getType(protocol);

       switch (eProtocol) {
           case modbus:{
              String hexFrame = protocolDTO.getHexFrame();
              byte[] frame = HexBin.stringToBytes(hexFrame);
              log.info("frame:" + HexBin.bytesToString(frame));
              byte[] crcBuff =  CrcUtils.makefcs(frame);
               log.info("crcBuff:" + HexBin.bytesToString(crcBuff));
              byte[] total =  ByteCombination.combinationContent(frame,crcBuff);
              String hexF = HexBin.bytesToString(total);
              rst.setHexFrame(hexF);
           }
           break;
       }
        log.info("rst:" + JSON.toJSONString(rst));
       return rst;
    }



}
